package com.github.tj123.frame.common.page;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import java.util.ArrayList;
import java.util.List;


public class PageUtils {

    public static <T> PageResponse<T> query(PageRequest request, PageQuery<T> query) throws Exception {
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getSize());
        List<T> list = query.query();
        if (list == null) {
            list = new ArrayList<T>();
        }
        PageResponse<T> response = new PageResponse<T>();
        response.setRows(list);
        response.setTotal(page.getTotal());
        return response;
    }

//    public static <T, ID extends Serializable, R extends MongoRepository<T, ID>>
//    PageResponse<T> queryM(PageRequest request, R repo, Sort sort) throws Exception {
//        org.springframework.data.domain.Page<T> page
//                = repo.findAll(new org.springframework.data.domain.PageRequest(request.getPage() - 1, request.getSize(), sort));
//        PageResponse<T> response = new PageResponse<>();
//        response.setRows(page.getContent());
//        response.setTotal(page.getTotalElements());
//        return response;
//    }
//
//    public static <T, ID extends Serializable, R extends MongoRepository<T, ID>>
//    PageResponse<T> query(PageRequest request, R repo, Example<T> example, Sort sort) throws Exception {
//        org.springframework.data.domain.PageRequest pageRequest =
//                new org.springframework.data.domain.PageRequest(request.getPage() - 1, request.getSize(), sort);
//        org.springframework.data.domain.Page<T> page = repo.findAll(example, pageRequest);
//        PageResponse<T> response = new PageResponse<>();
//        response.setRows(page.getContent());
//        response.setTotal(page.getTotalElements());
//        return response;
//    }
//
//    public static <T, ID extends Serializable, R extends MongoRepository<T, ID>>
//    PageResponse<T> queryM(PageRequest request, R repo) throws Exception {
//        return queryM(request, repo, null);
//    }
//
//    public static <T, ID extends Serializable, R extends MongoRepository<T, ID>>
//    PageResponse<T> query(PageRequest request, R repo, Example<T> example) throws Exception {
//        return query(request, repo, example, null);
//    }
}
